# coding=utf-8
# from django.shortcuts import render_ex

# from GameBar.handler import register_url_handler, WebRequestHandler
# from .render import set_menu_selected
# from Apps.LN_game.views.render import render_ex
from Utils.url import get_media_url
from Web.err import *
from Web.menu import *
from Web.request import *
from .utils import *
from ..forms import *
from ..models import ProductModel as mProduct

ctx_set = {
    "edit_product_page_url": "/LN_game/product/page/edit/",
    "query_product_page_url": "/LN_game/product/page/query/",
    "add_product_page_url": "/LN_game/product/page/add/",
    "query_product_api_url": "/LN_game/product/api/query/",
    "add_product_api_url": "/LN_game/product/api/add/",
    "update_product_api_url": "/LN_game/product/api/update/",
    "delete_product_api_url": "/LN_game/product/api/delete/"
}

menus += [
    menu("产品管理", '/LN_game/product/page/query/')
]

@register_url_handler(R'^LN_game/product/page/edit/')
class EditProductActivity(WebRequestHandler):
    @login_required_ex(login_url="/LN_game/login/")
    def handler(self, request, data, files, *args):
        pro = mProduct.objects.get(id=int(data['id']))
        pro_form = ProductForm(instance=pro, initial={'id': int(data['id'])})
        pro.img_screen = get_media_url(pro_form['img_screen'].value().name)
        pro.img_confirm = get_media_url(pro_form['img_confirm'].value().name)
        pro.img_order = get_media_url(pro_form['img_order'].value().name)
        pro.img_recom_1 = get_media_url(pro_form['img_recom_1'].value().name)
        pro.img_recom_2 = get_media_url(pro_form['img_recom_2'].value().name)
        ctx_set.update({'product': pro})
        return html_render_ex(request, 'htmls/edit_product.html', ctx_set, ("产品管理"))


@register_url_handler(R'^LN_game/product/page/add/')
class AddProductActivity(WebRequestHandler):
    @login_required_ex(login_url="/LN_game/login/")
    def handler(self, request, data, files, *args):
        return html_render_ex(request, 'htmls/add_product.html', ctx_set, ("产品管理"))


@register_url_handler(R'^LN_game/product/page/query/')
class Query(WebRequestHandler):
    @login_required_ex(login_url="/LN_game/login/")
    def handler(self, request, data, files, *args):
        if data.has_key('id'):
            pass
        else:
            return html_render_ex(request, 'htmls/products.html', ctx_set, ("产品管理"))


@register_url_handler(R'^LN_game/product/api/query/')
class GetProductList(WebRequestHandler):
    def handler(self, request, data, files, *args):
        products = mProduct.objects.all().order_by('-recommended_value')
        resp_data = {
            'sEcho': data.get('sEcho'),
            'iTotalRecords': len(products),
            'iTotalDisplayRecords': len(products),
            'aaData': []
        }

        for m in products:
            prod_form = ProductForm(instance=m, initial={'id': m.pk})
            # print(prod_form['img_screen'].value())
            resp_data['aaData'].append({
                "id": prod_form['id'].value(),
                "name": prod_form['name'].value(),
                "status": prod_form['status'].value(),
                "img_screen": get_media_url(prod_form['img_screen'].value().name),
                "img_order": get_media_url(prod_form['img_order'].value().name),
                "img_confirm": get_media_url(prod_form['img_confirm'].value().name),
                "img_recom_1": get_media_url(prod_form['img_recom_1'].value().name),
                "img_recom_2": get_media_url(prod_form['img_recom_2'].value().name),
                "url": prod_form['url'].value(),
                "recommended_value": prod_form['recommended_value'].value()
            })

        return JsonResponse(resp_data)


@register_url_handler(R'^LN_game/product/api/add/')
class Add(WebRequestHandler):
    def handler(self, request, data, files, *args):
        pro_form = ProductForm(data, files)
        if not pro_form.is_valid():
            return json_resp(ErrInvalidForm())

        try:
            pro_form.save(True)
            return json_resp(ErrOk())
        except Exception as e:
            return json_resp(ErrSystem(e.message))


@register_url_handler(R'^LN_game/product/api/update/')
class Update(WebRequestHandler):
    def handler(self, request, data, files, *args):
        try:
            pro_model = mProduct.objects.get(pk=int(data['id']))
            pro_form = ProductForm(data, files, instance=pro_model)
            pro_form.save(True)
            return json_resp(ErrOk())
        except Exception as e:
            return json_resp(ErrSystem(e.message))


@register_url_handler(R'^LN_game/product/api/delete/')
class Delete(WebRequestHandler):
    def handler(self, request, data, files, *args):
        try:
            pro = mProduct.objects.get(pk=int(data['id']))
            pro.delete()
            return json_resp(ErrOk())
        except mProduct.DoesNotExist:
            return json_resp(ErrObjectNotFound())
        except Exception as e:
            return json_resp(ErrSystem(e.message))


@register_url_handler(R'^LN_game/product/api/query_with_rank/')
class Query(WebRequestHandler):
    def handler(self, request, data, files, *args):
        try:
            objs = []
            limit = data.get('limit', 8)
            pros = mProduct.objects.all().order_by('-recommended_value')[:int(limit)]
            for m in pros:
                prod_form = ProductForm(instance=m, initial={'id': m.pk})
                objs.append({
                    "id": prod_form['id'].value(),
                    "name": prod_form['name'].value(),
                    "status": prod_form['status'].value(),
                    "img_screen": get_media_url(prod_form['img_screen'].value().name),
                    "img_order": get_media_url(prod_form['img_order'].value().name),
                    "img_confirm": get_media_url(prod_form['img_confirm'].value().name),
                    "img_recom_1": get_media_url(prod_form['img_recom_1'].value().name),
                    "img_recom_2": get_media_url(prod_form['img_recom_2'].value().name),
                    "url": prod_form['url'].value(),
                    "recommended_value": prod_form['recommended_value'].value()
                })
            return json_resp(ErrOk(), objs)
        except Exception as e:
            return json_resp(ErrSystem(e.message))
